<ol class="breadcrumb">
  <li class="active"><%= @model.display_name %></li>
  <div class="pull-right">
    <a href="<%= path_for(format: "json", search: params[:search]) %>" target="_blank"><%= t :export_json %></a>
    &nbsp;&nbsp;&nbsp;
    <a href="<%= path_for(format: "xlsx", search: params[:search]) %>"><%= t :export_xlsx %></a>
    <% if @resources.new.writable? current_user %>
    &nbsp;&nbsp;&nbsp;
    <a href="<%= path_for "new" %>">+ <%= t :new %></a>
    <% end %>
  </div>
</ol>
<% if session[:flash] %>
  <div class="alert alert-success"><%= h session[:flash] %></div>
  <% session.delete(:flash) %>
<% end %>
<% if session[:alert] %>
  <div class="alert alert-danger"><%= h session[:alert] %></div>
  <% session.delete(:alert) %>
<% end %>
<table class="table">
<thead>
  <tr>
    <% @columns.each do |field| %>
    <th class="table-header"><a href="<%= path_for(sort: field.name == params[:sort] ? "-#{field.name}" : field.name) %>" style="color: #000;"><%= t field %></a> <span class="glyphicon glyphicon-search" data-name="<%= field.name %>"></span></th>
    <% end %>
    <th style="width: 150px;"><%= t :actions %></th>
  </tr>
</thead>
<tbody>
<%
  page = (params[:page] || 1).to_i
  total_page = (@resources.count + settings.pagination_size - 1) / settings.pagination_size
  pages =
    case
    when page < 3
      1..(total_page < 5 ? total_page : 5)
    when (total_page - page) < 3
      (total_page < 5 ? 1 : total_page - 5)..total_page
    else
      (page - 2)..(page + 2)
    end
%>
  <% @resources.skip(settings.pagination_size*(page-1)).limit(settings.pagination_size).each do |resource| %>
  <tr>
    <% @columns.each do |field| %>
      <td><%= present(resource, field) %></td>
    <% end %>
    <td>
      <a class="label label-primary" href="<%= path_for resource.id %>"><%= t :show %></a>
      <% if resource.writable? current_user %>
      <a class="label label-warning" href="<%= path_for resource.id, "edit" %>"><%= t :edit %></a>
      <% end %>
      <% if resource.deletable? current_user %>
      <a class="label label-danger" href="<%= path_for resource.id, "delete" %>" data-method="post" data-confirm="<%= t(:are_you_sure) %>"><%= t :delete %></a>
      <% end %>
    </td>
  </tr>
  <% end %>
</tbody>
</table>

<% if pages.count > 1 %>
<nav class="pull-right">
  <ul class="pagination">
    <li><a href="<%= path_for(page: 1) %>" aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li>
    <% pages.each do |p| %>
    <li class="<%= 'active' if p == page %>"><a href="<%= path_for(page: p) %>"><%= p %></a></li>
    <% end %>
    <li><a href="<%= path_for(page: total_page) %>" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>
  </ul>
</nav>
<% end %>

<script>
  $(".glyphicon-search").click(function() {
    var old = $("#_search").val();
    if (old.length > 0) {
      old = old + " ";
    }
    $("#_search").val(old + $(this).attr("data-name") + ":").focus();
  });
</script>
